<?php

/**
 * Description:
 *
 * @author      Eden
 * @datetime    2016/12/6 13:30
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */
class Show extends CI_Controller
{

    // 图片地址
    private $key = '';

    // 裁剪
    private $clip = false;

    // 缩放
    private $zoom = false;

    // 临时目录
    private $tmpDir = '/var/thumb_tmp';

    // Mime 类型
    private $mime = 'image/jpg';

    // 允许的格式
    private $formatArr = array('image/jpg', 'image/jpeg', 'image/png', 'image/gif');

    // 分隔符
    private $spl = '@';


    // -------------
    private $org = '';
    private $ext = '';
    private $width = 0;
    private $height = 0;

    private $orgSource = '';
    private $thumbDestFile = '';

    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
        $key = uri_string();
        if (empty($key)) {
            show_404();
            exit;
        }
        $this->key = '/' . ltrim($key, '/');
        $this->_check();
        $this->load->library('core/beansdb', 'beansdb');
    }

    public function view()
    {
        // 原图
        $thumb = explode($this->spl, $this->key);
        $thumbKey = str_replace('thumb/', '', $thumb[0]);
        $this->org = $thumbKey;

        // 扩展
        $dest = explode('.', $thumbKey);
        if (empty($dest)) {
            show_404();
            exit;
        }
        $this->ext = $dest[1];
        $this->thumbDestFile = $this->tmpDir. '/tmp' . '_' .uniqid(). $thumb[1];

        // 原图是否存在
        $this->_checkImageExists($this->org);

        // 获取参数
        $thumbParams = explode('.', $thumb[1]);
        $thumbOptions = explode('_', $thumbParams[0]);
        foreach ($thumbOptions as $thumbOption) {
            if (preg_match('/w(\d+)/', $thumbOption, $match)) {
                $this->width = (int)$match[1];
            }
            if (preg_match('/h(\d+)/', $thumbOption, $match)) {
                $this->height = (int)$match[1];
            }
        }

        // 获取原图
        $orignThumbSource = $this->_getOrgThumb();
        $this->orgSource  = $orignThumbSource;
        $thumbSrouceFile = rtrim($this->tmpDir, '/') . '/' . ltrim($thumbKey, '/');
        if (!file_exists($thumbSrouceFile) && is_file($thumbSrouceFile) !== true) {
            writeFile($thumbSrouceFile, $orignThumbSource);
        }

        $orignThumbSrouceInfo = getimagesize($thumbSrouceFile);
        // 还是这张图片的信息
        // 原始图片的宽高
        $w = $orignThumbSrouceInfo[0];
        $h = $orignThumbSrouceInfo[1];
        $this->mime = $orignThumbSrouceInfo['mime'];

        //// 动态图片无法处理，返回原图
        if(preg_match("/".chr(0x21).chr(0xff).chr(0x0b).'NETSCAPE2.0'."/",$orignThumbSource)){
            echo $orignThumbSource;
            exit;
        }

        if ($this->clip) {
            $this->_clip($w, $h);
        }

    }


    /**
     * 裁剪
     * @param $w
     * @param $h
     */
    private function _clip($w, $h)
    {
        // 根据uri的参数，计算需要裁剪图片的宽高比
        // 如果宽/高比例为 16:9, 4:3, 2:1, 3:1 则取对应缩略图作为源生成缩略图
        $generatFromThumb = true;
        $wph = $this->width / $this->height;
        if ((16 / 9 + 0.1) >= $wph && (16 / 9 - 0.1) <= $wph) {
            $wph = 16 / 9;
        } else if ((4 / 3 + 0.1) >= $wph && (4 / 3 - 0.1) <= $wph) {
            $wph = 4 / 3;
        } else if ((2 / 1 + 0.1) >= $wph && (2 / 1 - 0.1) <= $wph) {
            $wph = 2 / 1;
        } else if ((3 / 1 + 0.1) >= $wph && (3 / 1 - 0.1) <= $wph) {
            $wph = 3 / 1;
        } else {
            $generatFromThumb = false;
        }

        $thumbKey = $this->org;
        if ($generatFromThumb) {
            if ($w / $h >= $wph) {
                $th = $h;
                $tw = $th * $wph;
            } else {
                $tw = $w;
                $th = $tw / $wph;
            }
            $tw = intval($tw);
            $th = intval($th);

            $orignThumbKeyArray = explode('.', $this->org);
            $thumbKey = str_replace('/a/', '/a/thumb/', $this->org) . $this->spl . 'w' . $tw . '_h' . $th . '.' . array_pop($orignThumbKeyArray);
            $thumbSource = $this->beansdb->get($thumbKey);
            if (!$thumbSource) {
                $thumbKey = $this->org;
                $thumbSource = $this->orgSource;
            }
        } else {
            $thumbSource = $this->orgSource;
        }

        $thumbSrouceFile = rtrim($this->tmpDir, '/') . '/' . ltrim($thumbKey, '/');
        if (is_file($thumbSrouceFile) !== true) {
            writeFile($thumbSrouceFile, $thumbSource, false, true);
        }

        // 如果宽、高为0，返回原图比例
        $thumbSrouceInfo = getimagesize($thumbSrouceFile);
        $w = $thumbSrouceInfo[0];
        $h = $thumbSrouceInfo[1];
        if ($this->height == 0) {
            $this->height = $this->width * $h / $w;
        } elseif ($this->width == 0) {
            $this->width = $this->height * $w / $h;
        }
        $width = min($this->width, $w);
        $height = min($this->height, $h);

        // 对 PNG 图片不友好
        if (in_array(strtolower($this->ext), array('jpeg', 'jpg'))) {
            $tclip = tclip($thumbSrouceFile, $this->thumbDestFile, $width, $height);
            if (!$tclip) {
                show_404();
                exit;
            }
        } else {
            $this->load->library('image_lib');
            $config['source_image'] = $thumbSrouceFile;
            $config['create_thumb'] = TRUE;
            $config['maintain_ratio'] = TRUE;
            $config['new_image'] = $this->thumbDestFile;
            $config['thumb_marker'] = '';
            $config['width'] = $width;
            $config['height'] = $height;
            $this->image_lib->initialize($config);
            $this->image_lib->resize();
        }

        if (empty($thumbDest)) {
            $thumbDest = file_get_contents($this->thumbDestFile);
            // 删除临时文件
            if (is_file($thumbSrouceFile)) {
                @unlink($thumbSrouceFile);
            }

            if (is_file($this->thumbDestFile)) {
                @unlink($this->thumbDestFile);
            }

            try {
                $this->beansdb->save($this->key, $thumbDest);
            } catch (Exception $e) {}

            try {
                $this->db->insert('attachment_thumb', array('key' => $this->key));
            } catch(PDOException $e) {
                echo $e->getMessage();
                die;
            }
        }

        header("Content-type: $this->mime");
        echo $thumbDest;
    }

    // 获取原图
    private function _getOrgThumb()
    {
        return $this->beansdb->get($this->org);
    }

    /**
     * 检查图片是否存在
     * @param $org
     */
    private function _checkImageExists($org)
    {
        if (!$this->beansdb->has($org)) {
            show_404();
            exit;
        }
    }

    /**
     * 检查URL
     */
    private function _check()
    {
        // 图片裁剪
        $this->clip = preg_match('#/a/thumb/(\d+)/(\d+)/(.*)@w(\d+)_h(\d+)\.(jpe?g|png|gif)#i', $this->key, $matches);
        // 图片缩放
        $this->zoom = preg_match('#/a/thumb/(\d+)/(\d+)/(.*)!w(\d+)_h(\d+)\.(jpe?g|png|gif)#i', $this->key, $matches);
        // 格式校验
        if (!$this->clip && !$this->zoom) {
            show_404();
            exit;
        }

        if ($this->clip) {
            $this->spl = '@';
        } else if ($this->zoom) {
            $this->spl = '!';
        }

        $this->_checkTmp();
    }

    /**
     * 检查临时目录
     */
    private function _checkTmp()
    {
        if (!is_dir($this->tmpDir) || !file_exists($this->tmpDir)) {
            @mkdir($this->tmpDir, 0777, true);
        }
    }
}
